package com.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dao.StaffQiyeChangeRecordDao;
import com.pojo.Qiye;
import com.pojo.StaffQiyeChangeRecord;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class StaffQiyeChangeRecordService extends ServiceImpl<StaffQiyeChangeRecordDao, StaffQiyeChangeRecord> {

    @Autowired
    private QiyeService qiyeService;

    @Autowired
    private StaffQiyeChangeRecordDao staffQiyeChangeRecordDao;

    /**
     * 保存员工企业变更记录
     * @param oldQyId 修改前企业ID
     * @param newQyId 修改后企业ID
     * @param staffID 员工ID
     * @return
     */
    public int saveStaffQyChangeRecord (String oldQyId, String newQyId, String staffID) {
        StaffQiyeChangeRecord staffQiyeChangeRecord = new StaffQiyeChangeRecord();
        if (StringUtil.isNotNull(oldQyId)) {
//            Qiye oldQy = qiyeService.getById(oldQyId);
            Qiye oldQy = qiyeService.getOne(new QueryWrapper<Qiye>().eq("id",oldQyId).eq("status",1));
//            staffQiyeChangeRecord.setBeforeChangeQyId(oldQyId);
            if (oldQy != null) {
                staffQiyeChangeRecord.setBeforeChangeQyId(oldQyId);
                staffQiyeChangeRecord.setBeforeChangeWyId(oldQy.getWyID());
            }

            if (StringUtil.isNotNull(newQyId)){
                Qiye newQy = qiyeService.getById(newQyId);
                staffQiyeChangeRecord.setAfterChangeQyId(newQyId);
                if (newQy != null) {
                    staffQiyeChangeRecord.setAfterChangeWyId(newQy.getWyID());
                }
            }
            staffQiyeChangeRecord.setStaffId(staffID);
            staffQiyeChangeRecord.setOperDate(new Date());
            return staffQiyeChangeRecordDao.insert(staffQiyeChangeRecord);
        }
        return 0;
    }

    /**
     * 分页查询员工企业变更记录
     * @param page
     * @param limit
     * @param staffID   员工ID
     * @return
     */
    public IPage getChangeRecord(int page, int limit, String staffID){
        Page p = new Page(page,limit);
        QueryWrapper<StaffQiyeChangeRecord> q = new QueryWrapper();
        q.eq("staffId",staffID);
        q.orderByDesc("operDate");
        IPage iPage = staffQiyeChangeRecordDao.selectPage(p,q);
        return iPage;
    }
}
